package logic

import (
	"context"
	"fmt"
	"yktwo/models/mysql"
	"yktwo/models/redis"
	"yktwo/pkg"

	"yktwo/yktworpc/internal/svc"
	"yktwo/yktworpc/yktworpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *yktworpc.LoginRequest) (*yktworpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("sendSms" + in.Mobile + "login")
	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("短信未验证,请重新输入")
	}

	var user mysql.User
	mysql.DB.Debug().Model(&user).Where("mobile = ?", in.Mobile).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("账户未注册")
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码不正确,请重新输入")
	}

	redis.Client.Del("sendSms" + in.Mobile + "login")
	return &yktworpc.LoginResponse{Id: int64(user.ID)}, nil
}
